package com.moter.demo01.juc.basic;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class ReentrantLockDemo {
    public static void main(String[] args) {
        TicketLock ticket = new TicketLock();
        new Thread(()->{ for (int i = 0; i <40 ; i++) ticket.sale();},"A").start();
        new Thread(()->{ for (int i = 0; i <40 ; i++) ticket.sale();},"B").start();
        new Thread(()->{ for (int i = 0; i <40 ; i++) ticket.sale();},"C").start();
    }
}
class TicketLock {
    private int tickets = 30;
    private Lock lock = new ReentrantLock(true);//参数可以设置为是否公平
    public void sale(){
        lock.lock();
        try {
            if(tickets>0){
                System.out.println(Thread.currentThread().getName()+"卖出了第"+tickets--+"张票，还剩"+tickets+"张");
            }
        }finally {
            lock.unlock();
        }
    }

}
